/* @flow */

import { isRegExp, remove } from 'shared/util'
import { getFirstComponentChild } from 'core/vdom/helpers/index'

type VNodeCache = { [key: string]: ?VNode };

// 获取组件名称（通过组件选项options中的name值，或者opts.tag)
function getComponentName (opts: ?VNodeComponentOptions): ?string {
  return opts && (opts.Ctor.options.name || opts.tag)
}

// 判断name是否匹配pattern
function matches (pattern: string | RegExp | Array<string>, name: string): boolean {
  if (Array.isArray(pattern)) {
    return pattern.indexOf(name) > -1
  } else if (typeof pattern === 'string') {
    return pattern.split(',').indexOf(name) > -1
  } else if (isRegExp(pattern)) {
    return pattern.test(name)
  }
  /* istanbul ignore next */
  return false
}

// 移除keepAlive实例中的不满足filter函数的key
function pruneCache (keepAliveInstance: any, filter: Function) {
  const { cache, keys, _vnode } = keepAliveInstance
  for (const key in cache) {
    const cachedNode: ?VNode = cache[key]
    if (cachedNode) {
      const name: ?string = getComponentName(cachedNode.componentOptions)
      if (name && !filter(name)) {
        pruneCacheEntry(cache, key, keys, _vnode)
      }
    }
  }
}
// pruneCacheEntry负责将组件从缓存中删除，它会调用组件 $destroy 方法销毁组件实例，缓存组件置空，并移除对应的 key
function pruneCacheEntry (
  cache: VNodeCache,
  key: string,
  keys: Array<string>,
  current?: VNode
) {
  const cached = cache[key]
  if (cached && (!current || cached.tag !== current.tag)) {
    // 销毁vnode对应的vnode实例
    cached.componentInstance.$destroy()
  }
  // 从cache对象中移除vnode
  cache[key] = null
  // 从keys数组中移除对应的key
  remove(keys, key)
}

const patternTypes: Array<Function> = [String, RegExp, Array]

export default {
  name: 'keep-alive',
  abstract: true,

  props: {
    include: patternTypes,
    exclude: patternTypes,
    max: [String, Number]
  },

  created() {
    // 创建cache对象，用于存储vnode，格式为: { key: vnode }
    this.cache = Object.create(null)
    // 存储vnode对应的key
    this.keys = []
  },

  destroyed() {
    // 遍历this.cache中的key，并删除对应的缓存entry
    for (const key in this.cache) {
      pruneCacheEntry(this.cache, key, this.keys)
    }
  },

  mounted() {
    // 监控include、exclude的变化，并移除对应的cache对象
    this.$watch('include', val => {
      pruneCache(this, name => matches(val, name))
    })
    this.$watch('exclude', val => {
      pruneCache(this, name => !matches(val, name))
    })
  },

  render() {
    // 获取默认插槽, 它是一个vnode数组
    const slot = this.$slots.default
    // 获取第一个vnode
    const vnode: VNode = getFirstComponentChild(slot)
    // 函数式组件的vnode是没有componentOptions的（只有组件vnode才有），所以keep-alive不会缓存函数式组件
    const componentOptions: ?VNodeComponentOptions = vnode && vnode.componentOptions
    if (componentOptions) {
      // check pattern
      // 通过vnode.componentOptions，获取组件名称
      const name: ?string = getComponentName(componentOptions)
      const { include, exclude } = this
      if (
        // not included，在include中，但是名字没有，或名字不匹配
        (include && (!name || !matches(include, name))) ||
        // excluded，组件在excluded当中，并且name存在，并满足exclude的条件
        (exclude && name && matches(exclude, name))
      ) {
        // 直接返回vnode
        return vnode
      }

      const { cache, keys } = this
      // 获取vnode的key，作为唯一标识
      const key: ?string = vnode.key == null
        // same constructor may get registered as different local components so cid alone is not enough (#3269)
        ? componentOptions.Ctor.cid + (componentOptions.tag ? `::${componentOptions.tag}` : '')
        : vnode.key
      if (cache[key]) {
        // 缓存命中
        vnode.componentInstance = cache[key].componentInstance
        // make current key freshest
        // 保持当前key对应的那个vnode是新鲜的(移除老的那个key，并将新的key存到队列尾部)： LRU缓存策略
        remove(keys, key)
        keys.push(key)
      } else {
        // 缓存没有命中，则缓存vnode到cache[key]上
        cache[key] = vnode
        keys.push(key)
        // prune oldest entry
        // 如果超过了max值，则删除最老的那个vnode(keys数组中的第一个)
        if (this.max && keys.length > parseInt(this.max)) {
          pruneCacheEntry(cache, keys[0], keys, this._vnode)
        }
      }
      // 如果是keep-alive的组件，则在vnode的data上设置keepAlive属性为true，表示它是一个用keep-alive缓存的组件
      vnode.data.keepAlive = true
    }
    return vnode || (slot && slot[0])
  }
}
